<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="选择店铺" prop="storeId">
        <el-select class="width35" v-model="queryParams.storeId" placeholder="请选择店铺"
                   filterable clearable>
          <el-option v-for="(item,index) in storeList" :key="index"
                     :label="item.storeUserName + ' - ' + item.lable"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="店铺别名" prop="storeAlias">
        <el-input v-model="queryParams.storeAlias" placeholder="请输入店铺别名" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="handleAdd('0')">新增店铺</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="handleAdd('1')">新增关联店铺</el-button>
      </el-col>
    </el-row>
    <!--  店铺列表  -->
    <el-tabs type="border-card" @tab-click="tabsClick">
      <el-tab-pane v-for="item in tabsList" :key="item.value" :label="item.label" :name="item.value">
        <el-table v-loading="loading" :data="autoOperationStoreList" border stripe>
          <!--      <el-table-column type="selection" width="55" align="center"/>-->
          <el-table-column label="店铺别名" prop="storeAlias" align="center"/>
          <el-table-column label="店铺名称" prop="storeName" align="center"/>
          <el-table-column label="联系电话" prop="userMobile" align="center"/>
          <el-table-column label="绑定时间" prop="bindTime" align="center"/>
          <el-table-column label="授权过期时间" prop="expireTime" align="center">
            <!--            <template slot-scope="scope">-->
            <!--              {{ scope.row.expireTime.slice(0, -8) }}-->
            <!--            </template>-->
          </el-table-column>
          <el-table-column label="违规" prop="violationScore" align="center" width="100">
            <template slot-scope="scope">
              <span class="borderB changeHand text-blue inlineB" @click="goViolationLog(scope.row)">
                {{ scope.row.violationScore }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="是否开启自动提交订单" prop="isAutoSubmitOrder" align="center" width="100">
            <template slot-scope="scope">
              <el-switch :value="scope.row.isAutoSubmitOrder" :active-value="1" :inactive-value="0"
                         active-color="#13ce66" inactive-color="#ff4949"
                         @change="changeAutoSubmitOrder(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="余额" prop="walletMoney" align="center" width="100"/>
          <el-table-column label="测评余额" prop="evaluationMoney" align="center" width="100"/>
          <el-table-column label="未回复消息数量" prop="msgNumber" align="center" width="100">
            <template slot-scope="scope">
              <el-badge is-dot class="mt10" :hidden="scope.row.msgNumber == '0' ||  !scope.row.msgNumber">
                <div class="borderB changeHand text-blue inlineB" @click="goMessageList(scope.row)">
                  {{ scope.row.msgNumber ? scope.row.msgNumber : '0' }}
                </div>
              </el-badge>
            </template>
          </el-table-column>
          <el-table-column label="店铺服务分" prop="serviceScore" align="center" width="100">
            <template slot-scope="scope">
              <div class="borderB changeHand text-blue inlineB" @click="openTargetModel(scope.row)">
                {{ scope.row.serviceScore ? scope.row.serviceScore : '/' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" align="center" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.auto_config_status" :value="scope.row.status"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <!--          <el-button size="mini" type="text" @click="handleViewData(scope.row)">查看数据</el-button>-->
              <el-button size="mini" type="text" @click="handleViewConfig(scope.row)">查看配置</el-button>
              <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="mini" type="text" @click="handleDisable(scope.row)">
                {{ scope.row.status == '1' ? '禁用' : '启用' }}
              </el-button>
              <el-button v-if="scope.row.cookieStatus != '1'" size="mini" type="text" class="text-danger"
                         @click="handleCookie(scope.row)">提交Cookie
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <el-dialog :title="title" append-to-body :visible.sync="open" width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" size="small">
        <el-form-item label="店铺" prop="storeId" v-if="storeType=='0' && !form.id">
          <el-select @change="chooseStore" v-model="form.storeId" class="width4" placeholder="请选择店铺"
                     :disabled="form.id" filterable clearable>
            <el-option v-for="(item,index) in storeList" :key="index"
                       :label="item.storeUserName + ' - ' + item.lable"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺账号" prop="storeAlias" v-if="!form.id">
          <el-input v-model="form.storeAlias" :disabled="storeType=='0'" @blur="blurStoreAlias"
                    placeholder="请输入CN码"></el-input>
        </el-form-item>
        <el-form-item label="店铺名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入店铺名称"></el-input>
        </el-form-item>
        <el-form-item label="公司名称" prop="corporateName" v-if="storeType=='0'">
          <el-input v-model="form.corporateName" placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="公司法人" prop="legalPerson" v-if="storeType=='0'">
          <el-input v-model="form.legalPerson" placeholder="请输入公司法人"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="userMobile">
          <el-input v-model="form.userMobile" maxlength="11" placeholder="请输入联系电话"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <!--  提交cookie弹窗  -->
    <submitCookie v-if="isOpenSubmitCookieModal" @close="closeSubmitCookieModal" :storeId="storeId"
                  :storeUserName="storeUserName"/>
    <!-- 店铺指标表现 -->
    <TargetExpression v-if="isOpenTargetModel" @close="isOpenTargetModel = false"
                      :targetExpressionParams="targetExpressionParams"/>
  </div>
</template>

<script>
import {
  deleteConfigById,
  saveConfig,
  queryAutoStoreDetail,
  queryAutoStoreList, updateStatusStatus, setAutoSubmitStore
} from "@/api/autoOperation/autoStore";
import {getIdByStoreUserName, queryUserShopList} from "@/api/shop/index"
import {queryMessageNum} from "@/api/autoOperation/python";
import submitCookie from "@/views/shop/components/SubmitCookie.vue";
import TargetExpression from "@/views/automation/components/TargetExpression.vue";
import configIndex from "@/views/automation/configIndex.vue";
export default {
  name: "AutoStoreIndex",
  dicts: ['auto_config_status'],
  components: {
    configIndex,
    submitCookie,
    TargetExpression
  },
  data() {
    return {
      loading: false,
      showSearch: true,
      open: false,//是否打开新增配置模态框
      autoConfigValue: "0",
      isOpenConfigIndex: false,//是否打开配置首页组件
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: undefined,
        storeAlias: undefined,
        userId: this.$store.getters.userId,
        revision: 0
      },
      storeList: [],
      autoOperationStoreList: [],//自运营店铺列表
      total: 0,//数据总条数
      form: {},
      rules: {
        storeId: [{required: true, message: "请选择店铺", trigger: "change"}],
        storeName: [{required: true, message: "店铺名称不能为空", trigger: "blur"}],
        storeAlias: [{required: true, message: "店铺别名不能为空", trigger: "blur"}],
        userMobile: [{required: true, trigger: "blur", validator: this.$Validate.isPhone}],
        cookie: [{required: true, message: "cookie不能为空", trigger: "blur"}],
        legalPerson: [{required: true, message: "公司法人不能为空", trigger: "blur"}],
        corporateName: [{required: true, message: "公司名称不能为空", trigger: "blur"}],
      },
      title: "",
      isOpenSubmitCookieModal: false,//是否打开提交cookie弹窗
      storeId: "",
      storeUserName: "",
      storeType: "",// 0：自己的店铺，1：客户的店铺
      tabsList: [{label: '店铺列表', value: '0'}, {value: '1', label: "关联店铺"}],
      isOpenTargetModel: false,//店铺指标
      targetExpressionParams: {},
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },
  created() {
    this.getList()
    // this.timeTask()
    this.getStoreList()
  },
  methods: {
    // 是否开启自动提交订单
    changeAutoSubmitOrder(row) {
      // console.log('row', row)
      let data = {
        id: row.id,
        type: row.isAutoSubmitOrder == '0' ? '1' : '0'
      }
      let message = row.isAutoSubmitOrder == '1' ? '关闭' : '开启';
      this.$confirm('是否确定' + message + '自动提交订单？').then(() => {
        setAutoSubmitStore(data).then(res => {
          this.getList()
          this.$message.success(res.msg)
        })
      })
    },
    // 切换选项卡
    tabsClick(tab, event) {
      this.queryParams.revision = tab.name
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 定时任务
    timeTask() {
      this.timer = setInterval(() => {
        this.getList()
      }, 10000)
      this.$once('hook:beforeDestory', () => {
        clearInterval(this.timer)
      })
    },
    // 选择店铺
    chooseStore(e) {
      if (e) {
        this.form.storeAlias = this.storeList.filter((val) => {
          return val.value == e
        })[0].storeUserName
      }
    },
    // 提交cookie
    handleCookie(row) {
      this.storeId = row.storeId;
      this.storeUserName = row.storeAlias
      this.isOpenSubmitCookieModal = true
    },
    // 关闭提交cookie弹窗
    closeSubmitCookieModal() {
      this.isOpenSubmitCookieModal = false
      this.getList()
    },
    // 跳转违规记录
    goViolationLog(row) {
      this.$router.push({
        path: "violation/violationLog",
        query: {
          storeId: row.storeId,
        }
      })
    },
    // 跳转消息列表
    goMessageList(row) {
      this.$router.push({
        path: "./messageList",
        query: {
          cookie_str: row.cookie,
        }
      })
    },
    // 打开标记表现弹窗
    openTargetModel(row) {
      let data = {
        cookie_str: row.cookie,
        channelId: row.channelId,
        proxy: row.bindLoginIp
      }
      this.targetExpressionParams = data
      this.isOpenTargetModel = true
    },
    // 获取自动化店铺列表
    getList() {
      this.loading = true
      queryAutoStoreList(this.queryParams).then(res => {
        let data = res.data
        this.total = data.total
        this.getSuppData(data.list)
      })
    },
    // 获取补充数据
    getSuppData(list) {
      this.autoOperationStoreList = list
      list.forEach((item) => {
        if (item.channelId) {
          let data = {
            cookie_str: item.cookie,
            channelId: item.channelId,
            proxy: item.bindLoginIp
          }
          this.getMessageNum(data, item)
        }
      })
      setTimeout(() => {
        this.loading = false;
      }, 2500)
    },
    // 获取消息数量
    getMessageNum(data, item) {
      queryMessageNum(data).then(res => {
        let data = res.data
        this.$set(item, "msgNumber", data.data.toString())
        this.$set(item, "serviceScore", data.score.toString())
        this.$set(item, "cookieStatus", '1')
      }).catch((error) => {
        let {message} = error;
        if (message.substr(message.length - 3) == '503') {
          item.cookieStatus = '0'
          this.$set(item, "cookieStatus", '0')
        }
      })
    },
    // 禁用
    handleDisable(row) {
      this.$confirm('是否要修改该配置状态？').then(() => {
        updateStatusStatus({id: row.id}).then(res => {
          this.$message.success(res.msg)
          this.getList()
        })
      })
    },
    // 查看数据
    handleViewData(row) {
      this.$router.push({
        path: "./dataDisplay",
        query: {
          storeId: row.storeId,
          id: row.id
        }
      })
    },
    // 查看配置
    handleViewConfig(row) {
      this.$router.push({
        path: "./configIndex",
        query: {
          storeId: row.storeId
        }
      })
      // this.isOpenConfigIndex = true
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      queryAutoStoreDetail({id: row.id}).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改自动化店铺信息";
      });
    },
    // 删除数据
    handleDelete(row) {
      const ids = row.id || this.ids.toString();
      this.$modal.confirm('是否确认删除该用户数据？').then(() => {
        this.loading = true;
        deleteConfigById({id: ids}).then(res => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess(res.msg);
        })
      })
    },
    reset() {
      this.form = {
        id: undefined,
        storeId: undefined,
        storeName: undefined,
        storeAlias: undefined,
        userMobile: undefined,
        bindTime: undefined,
        cookie: undefined,
        legalPerson: undefined,
        corporateName: undefined,
        userId: this.$store.getters.userId,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //  获取店铺列表
    getStoreList() {
      queryUserShopList().then(response => {
        this.storeList = response.data
      })
    },
    handleAdd(type) {
      this.reset();
      this.title = "新增自动化店铺"
      this.storeType = type
      this.open = true
    },
    // 输入店铺账号
    blurStoreAlias(e) {
      getIdByStoreUserName({storeUserName: this.form.storeAlias}).then(res => {
        this.form.storeName = res.data.storeName
        this.form.userMobile = res.data.storePhone
        this.form.storeId = res.data.id
        this.form.revision = this.storeType
      })
    },
    // 确定提交表单
    dataFormSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          saveConfig(this.form).then(res => {
            this.open = false
            this.getList()
            this.$message.success(res.msg)
          })
          // getIdByStoreUserName({storeUserName: this.form.storeAlias}).then(response => {
          //   this.form.storeId = response.id
          //   this.form.revision = this.storeType
          //
          // })
        }
      })
    },
    cancel() {
      this.open = false
    },
    close() {
      this.isOpenConfigIndex = false
    }
  }
}
</script>

<style scoped>

</style>
